<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="search">
        <el-input
          v-model="queryParams.search"
          placeholder="请输入关键词"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable size="small">
          <el-option
            v-for="dict in categoryOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="college" v-if="queryParams.category === '专业'">
        <el-input
          v-model="queryParams.college"
          placeholder="请输入学院"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专业" prop="major" v-if="queryParams.category === '专业'">
        <el-input
          v-model="queryParams.major"
          placeholder="请输入专业"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          :disabled="single"
          @click="handleFile"
        >文件管理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="baseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="false" />
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="category">
        <template slot-scope="scope">
          <dict-tag :options="categoryOptions" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="学院" align="center" prop="college" v-if="showCollegeColumn" />
      <el-table-column label="专业" align="center" prop="major" v-if="showMajorColumn" />
      <el-table-column label="创建者" align="center" prop="creator" width="100" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updater" width="100" />
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleFile(scope.row)"
          >文件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改知识库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入知识库描述" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" @change="handleCategoryChange">
            <el-option
              v-for="dict in categoryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学院" prop="collegeDeptId" v-if="form.category === '专业'">
          <treeselect
            v-model="form.collegeDeptId"
            :options="collegeOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择学院"
            @select="handleCollegeSelect"
          />
        </el-form-item>
        <el-form-item label="专业" prop="majorDeptId" v-if="form.category === '专业' && form.collegeDeptId">
          <treeselect
            v-model="form.majorDeptId"
            :options="majorOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择专业（可选）"
            @select="handleMajorSelect"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listKnowledgeBase, getKnowledgeBase, delKnowledgeBase, addKnowledgeBase, updateKnowledgeBase } from "@/api/knowledge/base";
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "KnowledgeBase",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库表格数据
      baseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分类字典
      categoryOptions: [
        { dictLabel: "通用", dictValue: "通用" },
        { dictLabel: "专业", dictValue: "专业" }
      ],
      // 学院部门选项
      collegeOptions: [],
      // 专业部门选项
      majorOptions: [],
      // 是否显示学院列
      showCollegeColumn: false,
      // 是否显示专业列
      showMajorColumn: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        search: undefined,
        category: undefined,
        college: undefined,
        major: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "知识库名称不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "知识库分类不能为空", trigger: "change" }
        ],
        collegeDeptId: [
          { required: true, message: "请选择学院", trigger: "change" }
        ],
        majorDeptId: [
          { required: false, message: "请选择专业", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getColleges();
  },
  methods: {
    /** 查询知识库列表 */
    getList() {
      this.loading = true;
      listKnowledgeBase(this.queryParams).then(response => {
        this.baseList = response.rows;
        this.total = response.total;
        this.loading = false;

        // 判断是否需要显示学院和专业列
        this.showCollegeColumn = false;
        this.showMajorColumn = false;
        this.baseList.forEach(item => {
          if (item.category === '专业') {
            if (item.college) this.showCollegeColumn = true;
            if (item.major) this.showMajorColumn = true;
          }
        });
      });
    },
    // 查询学院列表
    getColleges() {
      listDept().then(response => {
        this.collegeOptions = this.handleTree(response.data, "deptId");
      });
    },
    // 转换部门数据结构
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 学院选择事件
    handleCollegeSelect(node) {
      this.form.college = node.deptName;
      this.form.major = null;
      this.form.majorDeptId = null;
      
      // 获取所选学院的子部门作为专业选项
      this.majorOptions = node.children ? [{ 
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }] : [];
    },
    // 专业选择事件
    handleMajorSelect(node) {
      this.form.major = node.deptName;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        description: undefined,
        category: undefined,
        college: undefined,
        major: undefined,
        collegeDeptId: undefined,
        majorDeptId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 分类变更
    handleCategoryChange(value) {
      if (value !== '专业') {
        this.form.college = undefined;
        this.form.major = undefined;
        this.form.collegeDeptId = undefined;
        this.form.majorDeptId = undefined;
      } else {
        // 如果选择专业分类，重新加载学院列表
        this.getColleges();
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加知识库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getKnowledgeBase(id).then(response => {
        this.form = response.data;
        // 如果是专业类型，需要重新加载学院和专业选项
        if (this.form.category === '专业') {
          this.getColleges();
        }
        this.open = true;
        this.title = "修改知识库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateKnowledgeBase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addKnowledgeBase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除知识库？删除后，知识库中的文件也将被删除，且无法恢复。').then(function() {
        return delKnowledgeBase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 文件管理按钮操作 */
    handleFile(row) {
      const id = row.id || this.ids[0];
      this.$router.push({
        path: `/knowledge/file/index/${id}`,
        query: {
          knowledgeName: row.name || this.baseList.find(item => item.id === id).name
        }
      });
    }
  }
};
</script>
